var express = require('express');
var router = express.Router();
var _ = require('underscore');
var Movie = require('../models/movie');

router.post("/movie/new", function (req, res, next) {
    var movieObj = req.body.movie;
    var id = movieObj._id;
    var _movie;
    if (id !== 'undefined') {
        Movie.findById(id, function (err, movie) {
            _movie = _.extend(movie, movieObj);

            _movie.save(function (err, movie) {
                res.redirect('/movie/' + movie._id);
            });
        })
    } else {
        _movie = new Movie({
            title: movieObj.title,
            doctor: movieObj.doctor,
            language: movieObj.language,
            country: movieObj.country,
            summary: movieObj.summary,
            flash: movieObj.flash,
            poster: movieObj.poster,
            year: movieObj.year
        });

        _movie.save(function (err, movie) {
            res.redirect('/movie/' + movie._id);
        });
    }
})

router.get("/movie", function (req, res, next) {
    res.render("admin", {
        title: "后台录入页",
        movie: {
            title: '',
            language: '',
            doctor: '',
            country: '',
            summary: '',
            flash: '',
            poster: '',
            year: new Date().getFullYear(),
            meta: {
                crateAt: {
                    type: Date,
                    default: Date.now()
                },
                updateAt: {
                    type: Date,
                    default: Date.now()
                }
            }
        }
    })
});

router.get("/update/:id", function (req, res, next) {
    var id = req.params.id;
    Movie.findOne({_id: id}, function (err, movie) {
        res.render("admin", {
            title: "后台录入更新页",
            movie: movie
        });
    })
});

router.delete("/list", function (req, res, next) {
    var id = req.query.id;
    Movie.remove({_id: id}, function (err, movie) {
        res.json({success: 1})
    })
});

router.get("/list", function (req, res, next) {
    Movie.find({}, function (err, movies) {
        res.render('list', {
            title: '列表页',
            movies: movies
        });
    })
});
module.exports = router;